"""
评估结果数据模型
"""
import uuid
from datetime import datetime
from sqlalchemy import (
    Column, String, Integer, Text, TIMESTAMP,
    ARRAY, Index, CheckConstraint, text, Numeric, ForeignKey
)
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.orm import relationship
from app.db.session import Base


class Assessment(Base):
    """评估结果表"""
    __tablename__ = "assessments"
    
    # 主键
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    
    # 外键
    record_id = Column(
        UUID(as_uuid=True),
        ForeignKey("medical_records.id", ondelete="CASCADE"),
        nullable=False,
        comment="病历ID"
    )
    
    # 评估模式
    evaluation_mode = Column(
        String(20),
        nullable=False,
        comment="评估模式：rule-based/ai-based/hybrid"
    )
    
    # 综合评分
    overall_score = Column(
        Integer,
        nullable=False,
        comment="综合评分(0-100)"
    )
    
    # 各维度评分
    completeness_score = Column(
        Integer,
        nullable=True,
        comment="完整性评分(0-100)"
    )
    standardization_score = Column(
        Integer,
        nullable=True,
        comment="规范性评分(0-100)"
    )
    consistency_score = Column(
        Integer,
        nullable=True,
        comment="一致性评分(0-100)"
    )
    accuracy_score = Column(
        Integer,
        nullable=True,
        comment="准确性评分(0-100)"
    )
    
    # 维度权重
    completeness_weight = Column(Numeric(3, 2), default=0.30, comment="完整性权重")
    standardization_weight = Column(Numeric(3, 2), default=0.25, comment="规范性权重")
    consistency_weight = Column(Numeric(3, 2), default=0.25, comment="一致性权重")
    accuracy_weight = Column(Numeric(3, 2), default=0.20, comment="准确性权重")
    
    # 评估总结
    summary = Column(Text, nullable=True, comment="评估总结")
    suggestions = Column(ARRAY(Text), nullable=True, comment="改进建议")
    
    # AI评估结果
    ai_response = Column(JSONB, nullable=True, comment="AI原始响应")
    
    # 元数据
    assessed_at = Column(
        TIMESTAMP,
        nullable=False,
        server_default=text("CURRENT_TIMESTAMP"),
        comment="评估时间"
    )
    assessment_duration = Column(Integer, nullable=True, comment="评估耗时(ms)")
    
    # 状态
    status = Column(
        String(20),
        default="completed",
        comment="状态：pending/processing/completed/failed"
    )
    
    # 关系
    record = relationship("MedicalRecord", back_populates="assessments")
    issues = relationship(
        "AssessmentIssue",
        back_populates="assessment",
        cascade="all, delete-orphan"
    )
    
    # 约束
    __table_args__ = (
        CheckConstraint(
            "overall_score >= 0 AND overall_score <= 100",
            name="check_overall_score_range"
        ),
        CheckConstraint(
            "completeness_score >= 0 AND completeness_score <= 100",
            name="check_completeness_score_range"
        ),
        CheckConstraint(
            "standardization_score >= 0 AND standardization_score <= 100",
            name="check_standardization_score_range"
        ),
        CheckConstraint(
            "consistency_score >= 0 AND consistency_score <= 100",
            name="check_consistency_score_range"
        ),
        CheckConstraint(
            "accuracy_score >= 0 AND accuracy_score <= 100",
            name="check_accuracy_score_range"
        ),
        CheckConstraint(
            "evaluation_mode IN ('rule-based', 'ai-based', 'hybrid')",
            name="check_evaluation_mode"
        ),
        CheckConstraint(
            "status IN ('pending', 'processing', 'completed', 'failed')",
            name="check_status"
        ),
        Index("idx_assessments_record_id", "record_id"),
        Index("idx_assessments_overall_score", "overall_score"),
        Index("idx_assessments_assessed_at", "assessed_at"),
    )
    
    def __repr__(self):
        return f"<Assessment(id={self.id}, score={self.overall_score})>"


class AssessmentIssue(Base):
    """问题详情表"""
    __tablename__ = "assessment_issues"
    
    # 主键
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    
    # 外键
    assessment_id = Column(
        UUID(as_uuid=True),
        ForeignKey("assessments.id", ondelete="CASCADE"),
        nullable=False,
        comment="评估ID"
    )
    
    # 问题信息
    issue_type = Column(
        String(50),
        nullable=False,
        comment="问题类型：completeness/standardization/consistency/accuracy"
    )
    severity = Column(
        String(20),
        nullable=True,
        comment="严重程度：critical/major/minor/info"
    )
    field_name = Column(String(200), nullable=True, comment="问题字段名")
    issue_description = Column(Text, nullable=False, comment="问题描述")
    suggestion = Column(Text, nullable=True, comment="改进建议")
    
    # 评分影响
    score_deduction = Column(Integer, default=0, comment="扣分")
    
    # 元数据
    created_at = Column(
        TIMESTAMP,
        nullable=False,
        server_default=text("CURRENT_TIMESTAMP")
    )
    
    # 关系
    assessment = relationship("Assessment", back_populates="issues")
    
    # 约束
    __table_args__ = (
        CheckConstraint(
            "severity IN ('critical', 'major', 'minor', 'info')",
            name="check_severity"
        ),
        Index("idx_assessment_issues_assessment_id", "assessment_id"),
        Index("idx_assessment_issues_type", "issue_type"),
        Index("idx_assessment_issues_severity", "severity"),
    )

